import { Button, Form, message } from 'antd';
import { ReactNode, useState } from 'react';
import router from 'next/router';
import SlidingPane from 'react-sliding-pane';
import 'react-sliding-pane/dist/react-sliding-pane.css';
import IconButton from './iconbutton';

export default function EditButton({
	buttonicon = '/icons/edit.svg',
	label = '编辑',
	children,
	dlgtitle,
	onSave,
	onShow
}: {
	label?: string;
	buttonicon?: string;
	children: ReactNode;
	dlgtitle: string;
	onSave(): Promise<true | string | void | null>;
	onShow?(): unknown;
}) {
	const [visible, setvisible] = useState(false);
	return <>
		<IconButton img={buttonicon} label={label} onClick={() => {
			onShow && onShow();
			setvisible(true);
		}} />
		<SlidingPane
			className='pane'
			isOpen={visible}
			title={dlgtitle || '编辑'}
			from="right"
			width="50rem"
			onRequestClose={() => {
				setvisible(false);
			}}
		>
			<Form
				layout='horizontal'
				labelCol={{ span: 6 }}
				wrapperCol={{ span: 16 }}
			>
				{children}
				<div className='footer'>
					<Button type='primary' onClick={async () => {
						try {
							const data = await onSave();
							if (data === true) {
								message.success({ content: '保存成功' });
								router.reload();
							} else {
								data && message.error({ content: data });
							}
							// setvisible(false);
						} catch (error) {
							console.error(error);
						}
					}} >保存</Button>
				</div>
			</Form>
		</SlidingPane>
		<style jsx>{`
.footer{
	display: flex;
	justify-content: center;
}
`}</style>
	</>;
}
